package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.common.util.DateUtil;
import com.egu.common.util.UserUtil;
import com.egu.mapper.TbClassMapper;
import com.egu.model.ClassSubject;
import com.egu.model.TbClass;
import com.egu.model.TbClassExample;
import com.egu.model.TbClassExample.Criteria;
import com.egu.model.User;
import com.egu.service.ClassService;
import com.egu.service.ClassSubjectService;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;

@Service
public class ClassServiceImpl implements ClassService {
	@Autowired
	TbClassMapper tbClassMapper;

	@Autowired
	ClassSubjectService classSubjectService;

	@Override
	public RequestPageVo<TbClass> getList(PageParam param, TbClass tbClass) {
		RequestPageVo<TbClass> result = new RequestPageVo<TbClass>();
		TbClassExample example = new TbClassExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsUsedEqualTo((byte) 1);
		if (StringUtils.isNotBlank(tbClass.getClassName())) {
			criteria.andClassNameLike("%" + tbClass.getClassName() + "%");
		}

		int count = (int) tbClassMapper.countByExample(example);
		if (count > 0) {
			example.setStartPage(param.getOffset());
			example.setPageSize(param.getLimit());
			List<TbClass> list = tbClassMapper.selectByExample(example);
			result.setRows(list);
			result.setTotal(count);
		}
		return result;
	}

	@Override
	@Transactional
	public RequestResultVo<TbClass> saveOrUpdate(TbClass tbClass) {
		ClassSubject classSubject = classSubjectService.getDataById(tbClass.getSubjectId());
		tbClass.setClassSubject(classSubject.getSubjectName());
		User currentUser = UserUtil.getCurrentUser();
		if (tbClass.getId() == null) {
			tbClass.setCreateor(currentUser.getUserName());
			tbClass.setCreateTime(DateUtil.getCurrentDate());
			tbClassMapper.insertSelective(tbClass);
		} else {

			tbClass.setModifier(currentUser.getUserName());
			tbClass.setModifiedTime(DateUtil.getCurrentDate());
			tbClassMapper.updateByPrimaryKeySelective(tbClass);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<TbClass> deleteDataById(Integer id) {
		User currentUser = UserUtil.getCurrentUser();
		TbClass tbClass = new TbClass();
		tbClass.setId(id);
		tbClass.setIsUsed((byte) 0);
		tbClass.setModifier(currentUser.getUserName());
		tbClass.setModifiedTime(DateUtil.getCurrentDate());
		try {
			tbClassMapper.updateByPrimaryKeySelective(tbClass);
		} catch (Exception e) {
			return RequestResultVo.error("数据库删除失败");
		}
		return RequestResultVo.success();
	}

}
